package org.lib.rabbitmqhello;

import java.util.Arrays;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;

import org.lib.rabbitmqhello.config.RabbitConfig;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;

@SpringBootApplication
public class RabbitmqHelloApplication {

	private static Consumer<Object> cs = System.out::println;
	
	public static void main(String[] args) {
		ConfigurableApplicationContext ctx = SpringApplication.run(RabbitmqHelloApplication.class, args);
		
		// 调试用
//		studyContext(ctx);
	}
	
	public static void studyContext(ConfigurableApplicationContext ctx) {
		cs.accept("++++++studyContext++++++\nBeanDefinitionCount=" + ctx.getBeanDefinitionCount());
		String[] beanNames = ctx.getBeanDefinitionNames();
		cs.accept("beanNames.length=" + beanNames.length);
		cs.accept("输出Bean的名称：");
		Arrays.stream(beanNames).forEach((name)->{
			cs.accept("name=" + name);
		});
		
//		cs.accept("---");
//		Arrays.stream(beanNames).forEach((name)->{
//			cs.accept(String.format("name=%s, bean=%s", name, ctx.getBean(name).toString()));
//		});
		
		cs.accept("------studyContext------");
	}

}

//@Component
//@Order(1)
@Slf4j
@Deprecated
class TestRunner1 implements CommandLineRunner {

	@Autowired
	private RabbitTemplate rabbitTemplate;
	
	@Override
	public void run(String... args) throws Exception {
		/**
		 * 发送消息
		 * 看看 是否到 queue1、是否能监听到
		 */
		for (int i=0; i<10; i++) {
			log.info("发送msg-{}", i);
			
			// 默认交换机 AMQP default，默认的 routingKey=""，，怎么接收并处理？TODO
//			rabbitTemplate.convertAndSend("Simple msg-" + i + ", @" + new Date());
			
			// 默认交换机，routingKey=queue1，转发到 queue队列
			rabbitTemplate.convertAndSend(RabbitConfig.QUEUE_1, "default-Simple msg-" + i + ", @" + new Date());
			
			// ex1交换机=>queue1
			rabbitTemplate.convertAndSend(RabbitConfig.EXCHANGE_1, RabbitConfig.QUEUE_1, "ex1-Simple msg-" + i + ", @" + new Date());

			TimeUnit.SECONDS.sleep(1L);
		}
	}
	
}
